package web.handler

import manager.MQTTManager
import org.json.JSONObject
import web.request.Response

abstract class AbstractHandler(
    protected val json: JSONObject,
    protected val request: String
) : Runnable {

    companion object {

        const val CODE_OK = 0
        const val MSG_OK = "ok"

        const val MSG_TIMEOUT = "timeout"
        const val CODE_TIMEOUT = -2

        const val CODE_FAIL = -1

        const val FIELD_REQUEST = "request"
    }

    protected val webTopic = json.getString("webTopic")

    private fun sendResponse(resp: String) {
        MQTTManager.publish(webTopic, resp)
    }

    protected fun sendResponse(resp: JSONObject) {
        resp.put(FIELD_REQUEST, request)
        sendResponse(resp.toString())
    }

    override fun run() {

        try {
            val res = exec()

            res.put(FIELD_REQUEST, request)

            sendResponse(res.toString())
        } catch (e: Exception) {
            e.printStackTrace()

            val msg = e.message ?: "unknown"

            val resp = Response(msg, CODE_FAIL, request)
            sendResponse(resp.toString())
        }
    }

    abstract fun exec(): JSONObject
}